package com.linkoog.devtools.toolwindow_manager;

import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import java.awt.*;

/**
 *
 */
class ToolWindowPreferenceCellRenderer extends JLabel implements TableCellRenderer {
    private static final Color SELECTION_BACKGROUND = UIManager.getColor("Table.selectionBackground");
    private static final Color SELECTION_FOREGROUND = UIManager.getColor("Table.selectionForeground");
    private static final Border FOCUS_CELL_HIGHLIGHT_BORDER = UIManager.getBorder("Table.focusCellHighlightBorder");

    static final ToolWindowPreferenceCellRenderer AVAILABLE = new ToolWindowPreferenceCellRenderer(paler(Color.GREEN));

    static final ToolWindowPreferenceCellRenderer UNAFFECTED = new ToolWindowPreferenceCellRenderer(Color.WHITE);

    static final ToolWindowPreferenceCellRenderer UNAVAILABLE = new ToolWindowPreferenceCellRenderer(paler(Color.RED));

    @NotNull
    private static Color paler(@NotNull Color c) {
        final int r = ((c.getRed() << 1) + Color.WHITE.getRed() * 3) / 5;
        final int g = ((c.getGreen() << 1) + Color.WHITE.getGreen() * 3) / 5;
        final int b = ((c.getBlue() << 1) + Color.WHITE.getBlue() * 3) / 5;

        return new Color(r, g, b);
    }

    private final Color unselectedBackground;
    private final Color unselectedForeground;

    private ToolWindowPreferenceCellRenderer(@NotNull Color bg) {
        unselectedBackground = bg;
        unselectedForeground = Color.BLACK;
        setBackground(unselectedBackground);
        setForeground(unselectedForeground);
        setOpaque(true);
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        setBackground(isSelected ? SELECTION_BACKGROUND : unselectedBackground);
        setBorder(hasFocus ? FOCUS_CELL_HIGHLIGHT_BORDER : null);
        setForeground(isSelected ? SELECTION_FOREGROUND : unselectedForeground);
        setText(value == null ? "" : value.toString());

        return this;
    }
}
